import { ref, watch } from 'vue'
import { DEFAULT_CONFIG } from '../constants'

/**
 * 防抖组合式函数
 * @param {*} value 要防抖的值
 * @param {number} delay 延迟时间
 * @returns {Object} 防抖后的值
 */
export function useDebounce(value, delay = DEFAULT_CONFIG.debounceDelay) {
  const debouncedValue = ref(value.value || value)
  let timeoutId = null

  const updateDebouncedValue = (newValue) => {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }
    
    timeoutId = setTimeout(() => {
      debouncedValue.value = newValue
    }, delay)
  }

  // 如果传入的是ref，监听其变化
  if (value && typeof value === 'object' && 'value' in value) {
    watch(value, updateDebouncedValue, { immediate: true })
  } else {
    debouncedValue.value = value
  }

  return {
    debouncedValue: readonly(debouncedValue),
    updateDebouncedValue
  }
}

/**
 * 防抖函数组合式函数
 * @param {Function} fn 要防抖的函数
 * @param {number} delay 延迟时间
 * @returns {Function} 防抖后的函数
 */
export function useDebouncedFunction(fn, delay = DEFAULT_CONFIG.debounceDelay) {
  let timeoutId = null

  const debouncedFn = (...args) => {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }
    
    timeoutId = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }

  const cancel = () => {
    if (timeoutId) {
      clearTimeout(timeoutId)
      timeoutId = null
    }
  }

  const flush = (...args) => {
    cancel()
    fn.apply(this, args)
  }

  return {
    debouncedFn,
    cancel,
    flush
  }
}

/**
 * 搜索防抖组合式函数
 * @param {Function} searchFn 搜索函数
 * @param {number} delay 延迟时间
 * @returns {Object} 搜索相关的状态和方法
 */
export function useSearchDebounce(searchFn, delay = DEFAULT_CONFIG.debounceDelay) {
  const searchQuery = ref('')
  const isSearching = ref(false)
  const searchResults = ref([])
  
  const { debouncedFn: debouncedSearch } = useDebouncedFunction(async (query) => {
    if (!query.trim()) {
      searchResults.value = []
      isSearching.value = false
      return
    }

    isSearching.value = true
    try {
      const results = await searchFn(query)
      searchResults.value = results || []
    } catch (error) {
      console.error('搜索失败:', error)
      searchResults.value = []
    } finally {
      isSearching.value = false
    }
  }, delay)

  watch(searchQuery, (newQuery) => {
    debouncedSearch(newQuery)
  })

  const clearSearch = () => {
    searchQuery.value = ''
    searchResults.value = []
    isSearching.value = false
  }

  return {
    searchQuery,
    searchResults,
    isSearching,
    clearSearch
  }
}



